
const router = require('koa-router')();
const tags = require("../json/tags"); // 菜单
const { writeJson } = require("../sql/sql-json") // 写去json

// 查
router.get('/tags/pageMenus', (ctx) => {
  const { currpage = 1, paseSize = 20 } = ctx.query
  ctx.body = {
    status: "C0000",
    message: "成功",
    result: {
      currpage,
      paseSize,
      data: tags
    }
  }
})

// 增
router.post('/tags/insertMenu', (ctx) => {
  const { name, status } = ctx.request.body
  tags.push({
    id: +(tags[tags.length - 1].id) + 1, // 自增
    name,
    status
  })
  writeJson('tags', tags, () => {
    ctx.body = {
      status: "C0000",
      message: "插入成功",
      result: true
    }
  })
})

// 编辑
router.post('/tags/editMenu', (ctx) => {
  const { id, name, status } = ctx.request.body
  tags.find((item) => {
    if (id === item.id) {
      item.name = name
      item.status = status
      writeJson('tags', tags, () => {
        ctx.body = {
          status: "C0000",
          message: "编辑成功",
          result: true
        }
      })
    } else {
      ctx.body = {
        status: "E0002",
        message: "暂无数据",
        result: true
      }
    }
  })
})

// 禁用
router.post('/tags/enableMenu', (ctx) => {
  const { id, status } = ctx.request.body
  tags.find((item) => {
    if (id === item.id) {
      item.status = status
      writeJson('tags', tags, () => {
        ctx.body = {
          status: "C0000",
          message: "禁用成功",
          result: true
        }
      })
    } else {
      ctx.body = {
        status: "E0002",
        message: "暂无数据",
        result: true
      }
    }
  })
})

// 删除
router.post('/tags/deleteTags', (ctx) => {
  const { id } = ctx.request.body
  const index = tags.find((item) => item.id === id)
  if (index >= 0) {
    tags.splice(index, 1)
    writeJson('tags', tags, () => {
      ctx.body = {
        status: "C0000",
        message: "删除成功",
        result: true
      }
    })
  } else {
    ctx.body = {
      status: "E0002",
      message: "暂无数据",
      result: true
    }
  }
})

module.exports = router

